<template>
  <div>
    <el-dialog
      title="导出"
      :visible.sync="dialogVisible"
      width="500px"
      :before-close="closeAddDialog"
      :close-on-click-modal="false"
    >
      <el-form
        :model="addForm"
        :rules="rules"
        ref="refAddForm"
        label-width="80px"
      >
        <!-- <el-form-item size="small" label="组织机构" prop="orgId">
          <el-select
            v-model="addForm.orgId"
            filterable
            placeholder="请选择组织机构"
            style="width: 100%"
            @change="projectchange"
            v-loadMore="loadMore"
            size="small"
          >
            <el-option
              v-for="(item, i) in projectList"
              :key="i"
              :label="item.orgName"
              :value="item.id"
            >
            </el-option>
            <div
              class="div_box"
              v-loading="loading"
              :style="loading ? '' : 'display: none;'"
            ></div>
          </el-select>
        </el-form-item> -->

        <el-form-item size="small" label="时间" prop="timeData">
          <el-date-picker
            v-model="addForm.timeData"
            type="daterange"
            :picker-options="pickerOptions"
            value-format="yyyy-MM-dd"
            align="center"
            start-placeholder="开始时间"
            range-separator="至"
            end-placeholder="结束时间"
            style="width: 100%"
            :clearable="false"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeAddDialog" class="cancel-button"
          >取 消</el-button
        >
        <el-button
          size="small"
          class="confirm-button"
          @click="addSubmit"
          v-preventReClick="1000"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { reqAlarmTask, reqOrgList } from "@api/api";
import { mapState } from "vuex";
import loadMore from "@mixin/loadMore";

export default {
  props: ["targetId"],
  mixins: [loadMore],
  data() {
    return {
      //实现时间限制选择在一个月内而且不能超过当前时间
      pickerOptions: {
        onPick: ({ maxDate, minDate }) => {
          this.cuttentTime = minDate.getTime();
          if (maxDate) {
            this.cuttentTime = "";
          }
        },
        disabledDate: (time) => {
          //获取当前时间戳
          let myDate = new Date();
          let newY = myDate.getFullYear();
          let newM = myDate.getMonth() + 1;
          let newD = myDate.getDate();
          let oldTime =
            newY +
            "-" +
            (newM < 10 ? "0" + newM : newM) +
            "-" +
            (newD < 10 ? "0" + newD : newD) +
            " " +
            "23:59:59";
          // let oldTime="2022-7-5 23:59:59"
          oldTime = new Date(oldTime).getTime(); // 将中国时间转换成毫秒
          // 今天之后的时间不可选
          if (time.getTime() > oldTime) {
            //time.getTime() > Date.now()
            return true;
          }
          //选择日期范围为一个月
          if (this.cuttentTime != "") {
            const one = 30 * 24 * 3600 * 1000;
            const minTime = this.cuttentTime - one;
            const maxTime = this.cuttentTime + one;
            return time.getTime() < minTime || time.getTime() > maxTime;
          }
        },
      },
      dialogVisible: false,
      addForm: {
        orgId: "",
        taskName: "",
        timeData: [],
      },

      loading: false,
      sysInstanceIndex: 1,
      sysInstanceTotalPages: 10,
      projectList: [], //组织机构
      rules: {
        orgId: [
          {
            required: true,
            message: "请选择组织机构",
            trigger: ["blur", "change"],
          },
        ],
        timeData: [
          {
            required: true,
            message: "请选择有效期",
            trigger: "change",
          },
        ],
      },
      orgName: "",
    };
  },
  computed: {
    ...mapState(["user"]),
  },
  watch: {
    dialogVisible(e) {
      if (e) {
        this.projectList =
          this.user.roleName == "TENANT_ADMIN"
            ? [{ orgName: "全部", id: "0" }]
            : [];
      }
    },
  },
  methods: {
    projectchange(e) {
      // console.log(e);
      this.projectList.forEach((item) => {
        if (item.id == e) {
          this.orgName = item.orgName;
          return;
        }
      });
    },
    async loadMore() {
      if (this.sysInstanceIndex >= Math.ceil(this.sysInstanceTotalPages / 10))
        return;
      this.sysInstanceIndex++;
      this.loading = true;
      // 获取列表数据的方法
      await this.OrgList();
      this.loading = false;
    },
    // 获取组织机构
    async OrgList() {
      // console.log(this.user.roleName=='TENANT_ADMIN');
      var res = await reqOrgList( {
        userId: this.user.userId,
        roleName: this.user.roleName,
        tenantId: this.user.tenantId,
          type: "4"
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      // this.projectList=this.projectList.unshift({orgName:'全部',id:""})
      this.projectList = res.data.rows
    },
    addSubmit() {
      this.$refs.refAddForm.validate(async (valid) => {
        if (!valid) return;
        let params = {
          userId: this.user.userId,
          roleName: this.user.roleName,
          tenantId: this.user.tenantId,
          orgId: this.targetId,
          taskName: `${
            this.user.roleName == "TENANT_ADMIN"
              ? this.user.tenantName
              : this.orgName
          }告警日志(${this.addForm.timeData[0]}至${this.addForm.timeData[1]})`,
          startDate: this.addForm.timeData[0],
          endDate: this.addForm.timeData[1],
        };
        const res = await reqAlarmTask(params);
        if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
        this.$modal.notifySuccess("导出成功，请在任务管理中查看");
        this.$router.push({
          name: "exportTask",
          params: { orgId: this.targetId, orgName: this.orgName },
        });
        this.closeAddDialog();
      });
    },
    // 点击关闭弹框
    closeAddDialog() {
      this.$refs.refAddForm.resetFields();
      this.dialogVisible = false;
      this.sysInstanceIndex = 1;
      this.sysInstanceTotalPages = 10;
      this.projectList = [];
    },
  },
  mounted() {},
  deactivated() {
    if (this.$refs.refAddForm != null) {
      this.closeAddDialog();
    }
  },
};
</script>

<style lang="less" scoped>
@import url("../../common.less");

// 日期控件颜色
::v-deep .el-range-editor .el-range-input {
  color: @primaryContentTxt !important;
}

::v-deep .el-form-item__label {
  padding: 0 12px 0 0 !important;
}

// 下拉框加载开始
.div_box {
  height: 276px;
  position: absolute;
  top: -1px;
  left: -1px;
  width: 100%;
  z-index: 2016;
  // background: red;
  // opacity: 0.5;
}

::v-deep .el-loading-mask {
  border-radius: 4px;
}

// 下拉框加载结束

// 时间日期 至
::v-deep .el-range-editor--small .el-range-separator {
  line-height: 26px !important;
}
</style>
